# -*- coding: utf-8 -*-

from odoo import models, fields, api, exceptions


class SpeechVote(models.Model):
    _name = 'speech.vote'
    _description = '加油记录'
    _order = 'create_date desc'

    activity_id = fields.Many2one('speech.activity', string='活动', required=True, ondelete='cascade', index=True)
    user_id = fields.Many2one('wechat.user', string='加油用户', required=True, ondelete='cascade', index=True)
    
    # 新增：支持加油给报名记录
    registration_id = fields.Many2one('activity.item.registration', string='报名记录', ondelete='cascade', index=True)
    
    vote_line_ids = fields.One2many('speech.vote.line', 'vote_id', string='加油明细')
    vote_count = fields.Integer(string='加油数量', compute='_compute_vote_count', store=True)
    
    ip_address = fields.Char(string='IP地址')
    user_agent = fields.Char(string='User Agent')
    
    _sql_constraints = [
        # 改为：一个用户不能重复给同一个报名记录加油
        ('user_registration_unique', 'UNIQUE(user_id, activity_id, registration_id)', '您已经给TA加油过了！')
    ]

    @api.depends('vote_line_ids')
    def _compute_vote_count(self):
        for record in self:
            record.vote_count = len(record.vote_line_ids)

    @api.model
    def create(self, vals):
        # 检查加油时间
        activity = self.env['speech.activity'].browse(vals.get('activity_id'))
        
        if not activity.voting_enabled:
            raise exceptions.ValidationError('该活动未启用加油！')
        
        now = fields.Datetime.now()
        
        if now < activity.voting_start_time:
            raise exceptions.ValidationError('加油尚未开始！')
        
        if now > activity.voting_end_time:
            raise exceptions.ValidationError('加油已结束！')
        
        return super(SpeechVote, self).create(vals)


class SpeechVoteLine(models.Model):
    _name = 'speech.vote.line'
    _description = '加油明细'

    vote_id = fields.Many2one('speech.vote', string='加油记录', required=True, ondelete='cascade', index=True)
    activity_id = fields.Many2one('speech.activity', string='活动', related='vote_id.activity_id', store=True, index=True)
    user_id = fields.Many2one('wechat.user', string='加油用户', related='vote_id.user_id', store=True, index=True)
    candidate_id = fields.Many2one('speech.registration', string='候选人', required=True, ondelete='cascade', index=True)
    
    _sql_constraints = [
        ('vote_candidate_unique', 'UNIQUE(vote_id, candidate_id)', '不能重复加油给同一候选人！')
    ]

